import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import legacyPlugin from '@vitejs/plugin-legacy'
import dotenv from 'dotenv'
import fs from 'fs'

function pathResolve(dir: string) {
    // eslint-disable-next-line no-undef
    return resolve(__dirname, '.', dir)
}

try {
    // 根据环境变量加载环境变量文件
    // eslint-disable-next-line no-undef
    const file = dotenv.parse(fs.readFileSync(`.env.${process.env.NODE_ENV}`))
    // 根据获取的key给对应的环境变量赋值
    console.log(file)
    for (const key in file as object) {
        // eslint-disable-next-line no-undef
        process.env[key] = file[key]
    }
} catch (e) {
    console.error(e)
}

export default defineConfig({
    plugins: [
        vue(),
        legacyPlugin({
            targets: ['defaults', 'not IE 11'],
            polyfills: [],
            ignoreBrowserslistConfig: false,
            // corejs: false,
        }),
    ],
    resolve: {
        alias: {
            '@/': `${pathResolve('src')}/`,
            'test/': `${pathResolve('test')}/`,
        },
    },
    server: {
        // hostname: 'localhost',
        // 反向代理
        port: 8889,
        proxy: {
            '/api': {
                target: 'http://192.168.0.129:80',
                changeOrigin: true,
                rewrite: (path) => path.replace(/^\/api/, ''),
            },
        },
        // 是否开启 https
        https: false,
    },
    css: {
        preprocessorOptions: {
            less: {
                modifyVars: {
                    hack: `true; @import (reference) "${resolve('test/assets/css/index.less')}";`,
                    'text-color': 'rgba(0, 0, 0, 0.85)', // 主文本色
                    'theme-color': '#1890ff', // 主题色
                    'font-size-sm': '12px', // 基本文字大小 的几个字号
                    'font-size-base': '14px',
                    'font-size-lg': '16px',
                    'table-striped': '#fafafa', //列表斑马线颜色,
                },
                javascriptEnabled: true,
            },
        },
    },
})
